package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //登陆提交的是post请求：
        //username=qazwsx&password=1
        resp.setContentType("text/html; charset=utf-8");
        // 1. 获取到用户提交的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 2. 判定用户名密码是否正确
        User user = UserDao.selectByName(username);
        if (!password.equals(user.getPassword())) {
            // 登陆失败
            resp.getWriter().write("登陆失败");
            return;
        }
        // 设置 Session
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            return;
        }
        User user = (User)session.getAttribute("user");
        if (user.getUsername() == null) {
            resp.setStatus(403);
            return;
        }
        // 返回 200 表示已经登陆.
        resp.setStatus(200);
    }
}
